package com.benio.ycfdisplayer.displayer;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Looper;
import android.util.Log;
import android.view.View;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

/**
 * Wrapper for Android {@link View View}.
 * Created by zhangzhibin on 2016/8/30.
 */
public abstract class ViewTarget<V extends View> implements Target {
    private static final String TAG = "ViewTarget";
    protected final Reference<V> mView;

    public ViewTarget(V view) {
        this.mView = new WeakReference<V>(view);
    }

    @Override
    public V getView() {
        return mView.get();
    }

    @Override
    public boolean setDrawable(Drawable drawable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            V view = mView.get();
            if (view != null) {
                setDrawableInto(drawable, view);
                return true;
            }
        } else {
            Log.w(TAG, "Can't set a bitmap into view. You should call ImageLoader on UI thread for it.");
        }
        return false;
    }

    @Override
    public boolean setBitmap(Bitmap bitmap) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            V view = mView.get();
            if (view != null) {
                setBitmapInto(bitmap, view);
                return true;
            }
        } else {
            Log.w(TAG, "Can't set a bitmap into view. You should call ImageLoader on UI thread for it.");
        }
        return false;
    }

    /**
     * Should set drawable into incoming view. Incoming view is guaranteed not null.<br />
     * This method is called on UI thread.
     */
    protected abstract void setDrawableInto(Drawable drawable, V view);

    /**
     * Should set Bitmap into incoming view. Incoming view is guaranteed not null.< br />
     * This method is called on UI thread.
     */
    protected abstract void setBitmapInto(Bitmap bitmap, V view);
}
